package siec;

import java.io.*;
import java.net.Socket;
import java.util.LinkedList;

//Równolegle
public class Connection extends Thread {
	private String nick = "";

	private boolean isJoined = false;

	private Socket socket;

	private BufferedReader in;

	private PrintWriter out;

	public LinkedList<String> messagesQueue;

	public Connection(Socket socket) {
		try {
			in = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(), true);
		} catch (IOException ex) {
		}
                // kolejka wiadomości
		messagesQueue = new LinkedList<String>();
		this.socket = socket;
	}

	public void sendMessage(String s) {
		out.println(s);
	}

        @Override
	public void run() {
		String s;
		try {
                    //oczekiwanie na wiadomość przychodzącą
			while ((s = in.readLine()) != null) {
                            //kiedy otrzyma - dodaje do LinkedList
				messagesQueue.add(s);
			}
                        // jeśli skończy się połączenie to zamyka out, in i socket
			out.close();
			in.close();
		} catch (IOException ex) {
		}

		try {
			socket.close();
		} catch (Exception ex) {
		}
	}

	public void close() {
		try {
			socket.close();
		} catch (Exception ex) {
		}
	}

	public void setNick(String nick) {
		this.nick = nick;
	}

	public String getNick() {
		return nick;
	}

	public void setJoined(boolean b) {
		isJoined = b;
	}

	public boolean isJoined() {
		return isJoined;
	}

}
